import axios from "axios";
import config from "../config";
import { ElMessage } from 'element-plus'
import router from '../router'

const TOKEN_INVALID = 'Token认证失败，请重新登录'
const NETWORK_ERROR = '网络请求异常，请稍后重试'

const service = axios.create({
    baseURL: config.baseApi,
    // headers: {
    //     'Content-Type': 'application/x-www-form-urlencoded'
    // },
    timeout: 12000
})

// 请求拦截器
service.interceptors.request.use(req => {
    const { Authorization } = req.headers
    if(Authorization) req.headers.Authorization = "Bear "
    return req
})

// 响应拦截器
service.interceptors.response.use(res => {
    const {code, msg} = res.data
    if(code === 200) {
        return res.data
    } else if(code === 40001) {
        ElMessage.error(TOKEN_INVALID)
        setTimeout(() => {
            router.push('/login')
        }, 2000);
        return Promise.reject(TOKEN_INVALID)
    } else {
        ElMessage.error(msg || NETWORK_ERROR)
        return Promise.reject(NETWORK_ERROR)
    }
})

/**
 * 
 * @param {object} options 请求配置
 * @return 请求实例
 */
function request(options) {
    options.method = options.method || 'get'
    if(options.method.toLowerCase() === 'get') {
        options.params = options.data
    }

    if(config.env === 'prod') {
        service.defaults.baseURL = config.baseApi
    } else {
        service.defaults.baseURL = config.mock ? config.mockApi : config.baseApi
    }

    return service(options)
}

['get', 'post', 'put', 'delete', 'patch'].forEach(item => {
    request[item] = (url, data, options) => {
        return request({
            url,
            method: item,
            data,
            ...options
        })
    }
})

export default request

